package com.tebiecloud.yunst.server.controller.feign;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tebiecloud.common.model.ResultBody;
import com.tebiecloud.common.utils.ResultBodyUtils;
import com.tebiecloud.yunst.client.constants.ResultEnum;
import com.tebiecloud.yunst.client.model.entity.YunBankCard;
import com.tebiecloud.yunst.client.model.entity.YunStUser;
import com.tebiecloud.yunst.client.model.entity.YunTransfer;
import com.tebiecloud.yunst.client.model.entity.YunWithdrawApply;
import com.tebiecloud.yunst.client.model.vo.WithdrawInfoVO;
import com.tebiecloud.yunst.client.service.IYunWithdrawServiceClient;
import com.tebiecloud.yunst.server.service.*;
import com.tebiecloud.yunst.server.yunstservice.YunStService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

@RestController
@RequestMapping("/feign/yunwithdraw")
public class WithdrawApplyController implements IYunWithdrawServiceClient {

    @Value("${tebiecloud.yunst.withdrawAmount}")
    private int withdrawAmount;

    @Autowired
    private YunWithdrawApplyService yunWithdrawApplyService;

    @Autowired
    private YunBankCardService yunBankCardService;

    @Autowired
    private YunStUserService yunStUserService;

    @Autowired
    private YunTransferService yunTransferService;

    @Autowired
    private YunStService yunStService;

    @PostMapping("withdrawapply")
    @Override
    public ResultBody<WithdrawInfoVO> withdrawApply(@RequestParam(value = "userId") Long userId, @RequestParam(value = "amount") int amount) {
        WithdrawInfoVO withdrawInfoVO = new WithdrawInfoVO();
        int difference = 0;//提现所需的差额
        //校验金额是否小于最小提现标准
        if(amount<withdrawAmount){
            return ResultBodyUtils.build(ResultEnum.YUN_WITHDRAW_AMOUNT_FIAL.getCode(),ResultEnum.YUN_WITHDRAW_AMOUNT_FIAL.getMessage()+withdrawAmount);
        }
        //查询是否存在账号
        QueryWrapper<YunStUser> yunStUserQueryWrapper = new QueryWrapper<>();
        yunStUserQueryWrapper.eq("user_id",userId);
        YunStUser yunStUser = yunStUserService.getOne(yunStUserQueryWrapper);
        if(yunStUser==null){
            return ResultBodyUtils.build(ResultEnum.YUN_ST_USER_NOT_FIND.getCode(),ResultEnum.YUN_ST_USER_NOT_FIND.getMessage());
        }
        //查询是否绑定银行卡
        QueryWrapper<YunBankCard> yunBankCardQueryWrapper = new QueryWrapper<>();
        yunBankCardQueryWrapper.eq("user_id",userId);
        yunBankCardQueryWrapper.eq("status",1);
        YunBankCard yunBankCard = yunBankCardService.getOne(yunBankCardQueryWrapper);
        if(yunBankCard==null){
            return ResultBodyUtils.build(ResultEnum.YUN_BANK_CARD_NOT_FOUND.getCode(), ResultEnum.YUN_BANK_CARD_NOT_FOUND.getMessage());
        }
        //查询账号金额
        Map<String,String> balanceMap =  yunStService.queryBalance(yunStUser.getBizUserId());
        if(balanceMap.get("status").equals("error")){
            return ResultBodyUtils.build(ResultEnum.YUN_WITHDRAW_ACCOUNT_FIAL.getCode(), ResultEnum.YUN_WITHDRAW_ACCOUNT_FIAL.getMessage());
        }
        int balance = Integer.valueOf(balanceMap.get("allAmount"));
        if(balance<amount){
            difference = amount - balance;
        }
        if(difference>0){
            //从中间账转差额过来
            Map<String,String> transferMap = yunStService.applicationTransfer(yunStUser.getBizUserId(),new Long(difference));
            if(transferMap.get("status").equals("error")){
                return ResultBodyUtils.build(Integer.valueOf(transferMap.get("code")), transferMap.get("message"));
            }
            //插入转账记录表
            YunTransfer yunTransfer = new YunTransfer();
            yunTransfer.setSourceId(transferMap.get("normAccountSetNo"));
            yunTransfer.setTargetId(yunStUser.getBizUserId());
            yunTransfer.setRemark(transferMap.get("res"));
            yunTransfer.setAmount(difference);
            yunTransferService.save(yunTransfer);
        }
        //提现
        Map<String,Object> resultMap = yunWithdrawApplyService.yunwithdrawApply(userId,yunStUser.getBizUserId(),amount,yunBankCard.getCardNo());
        if(resultMap.get("status").equals("error")){
            return ResultBodyUtils.build(ResultEnum.YUN_WITHDRAW_ACCOUNT_FIAL.getCode(), ResultEnum.YUN_WITHDRAW_ACCOUNT_FIAL.getMessage());
        }
        //插入提现表
        YunWithdrawApply yunWithdrawApply = (YunWithdrawApply) resultMap.get("yunWithdrawApply");
        withdrawInfoVO.setNumber(yunWithdrawApply.getWithdrawId().toString());
        withdrawInfoVO.setAmount(yunWithdrawApply.getAmount());
        return ResultBodyUtils.ok(withdrawInfoVO);
    }

    @Override
    public ResultBody<WithdrawInfoVO> withdrawInfo(Long withdrawId) {
        WithdrawInfoVO withdrawInfoVO = new WithdrawInfoVO();
        YunWithdrawApply yunWithdrawApply = yunWithdrawApplyService.getById(withdrawId);
        //查询银行卡
        QueryWrapper<YunBankCard> yunBankCardQueryWrapper = new QueryWrapper<YunBankCard>();
        yunBankCardQueryWrapper.eq("card_no",yunWithdrawApply.getBankCardNo());
        YunBankCard yunBankCard = yunBankCardService.getOne(yunBankCardQueryWrapper);
        withdrawInfoVO.setNumber(withdrawId.toString());
        withdrawInfoVO.setAmount(yunWithdrawApply.getAmount());
        int length = yunWithdrawApply.getBankCardNo().length();
        withdrawInfoVO.setCardNo(yunWithdrawApply.getBankCardNo().substring(length-4,length));
        withdrawInfoVO.setFee(yunWithdrawApply.getFee());
        withdrawInfoVO.setName(yunBankCard.getName());
        withdrawInfoVO.setTax(yunWithdrawApply.getTax());
        withdrawInfoVO.setApplyTime(yunWithdrawApply.getApplyTime());
        withdrawInfoVO.setArrivedTime(withdrawInfoVO.getArrivedTime());
        withdrawInfoVO.setStatus(withdrawInfoVO.getStatus());
        return ResultBodyUtils.ok(withdrawInfoVO);
    }
}
